package cn.tedu.web.fqmz.servlet;

import cn.tedu.web.fqmz.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        String user = req.getParameter("u");
        String password = req.getParameter("p");
        String code = req.getParameter("c");
        System.out.println(user);
        System.out.println(password);
        System.out.println(code);

        HttpSession session = req.getSession();
        Object c = session.getAttribute("c");

        boolean isTrue = code != null && code.equals(c);
        if (!isTrue) {
            PrintWriter writer = resp.getWriter();
            writer.write("验证码错误！");
            writer.flush();
            writer.close();
            return;
        }
        String sql = "SELECT id FROM `user` WHERE username = ? AND password = MD5(?)";
        Integer id = JdbcUtils.select(sql, Integer.class, user, password);
//        String message = id != null && id > 0L ? "登陆成功" : "登陆失败";
        //指定响应内容为文本，且字符集为utf-8

//        PrintWriter writer = resp.getWriter();
//        writer.write(message);
//        writer.flush();
//        writer.close();
        if (id != null) {
            session.setAttribute("UID",id);
            resp.sendRedirect("/fqmz/");
        } else {
            resp.sendRedirect("/fqmz/login.jsp");
        }
    }
}
